using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.LMZWorkSchedule;
using WPF_MVVM_Test.Services.LMZWorkSchedule;

namespace WPF_MVVM_Test.MVVM_ViewModel.LMZWorkSchedule
{
    /// <summary>
    /// 报工质检页面的ViewModel
    /// </summary>
    public class WorkReportQualityViewModel : BaseViewModel
    {
        /// <summary>
        /// 页面导航事件 - 用于通知主窗口切换页面
        /// </summary>
        public static event Action<string, WorkReportQualityItem>? RequestNavigateToPage;
        private readonly WorkReportQualityService _workReportQualityService;
        private string _orderNameFilter = "";
        private string _statusFilter = "";
        private ObservableCollection<WorkReportQualityItem> _workReportQualityItems = new();
        private int _currentPageIndex = 1;
        private int _pageSize = 10;
        private int _totalCount = 0;
        private int _totalPage = 0;
        private bool _isLoading = false;
        private string _jumpToPage = "1";

        public WorkReportQualityViewModel()
        {
            _workReportQualityService = new WorkReportQualityService();

            // 初始化命令
            SearchCommand = CreateCommand(ExecuteSearch);
            RefreshCommand = CreateCommand(ExecuteRefresh);
            FirstPageCommand = CreateCommand(ExecuteFirstPage, CanExecuteFirstPage);
            PreviousPageCommand = CreateCommand(ExecutePreviousPage, CanExecutePreviousPage);
            NextPageCommand = CreateCommand(ExecuteNextPage, CanExecuteNextPage);
            LastPageCommand = CreateCommand(ExecuteLastPage, CanExecuteLastPage);
            GoToPageCommand = CreateCommand(ExecuteGoToPage, CanExecuteGoToPage);

            // 详情相关命令
            ViewDetailsCommand = CreateCommand<WorkReportQualityItem>(ExecuteViewDetails);

            // 订阅静态刷新事件
            RefreshDataRequested += async () => await LoadWorkReportQualityDataAsync();

            // 初始化加载数据
            _ = LoadWorkReportQualityDataAsync();
        }

        #region 属性

        /// <summary>
        /// 报工质检项目集合
        /// </summary>
        public ObservableCollection<WorkReportQualityItem> WorkReportQualityItems
        {
            get => _workReportQualityItems;
            set => SetProperty(ref _workReportQualityItems, value);
        }

        /// <summary>
        /// 工单名称过滤条件
        /// </summary>
        public string OrderNameFilter
        {
            get => _orderNameFilter;
            set => SetProperty(ref _orderNameFilter, value);
        }

        /// <summary>
        /// 状态过滤条件
        /// </summary>
        public string StatusFilter
        {
            get => _statusFilter;
            set => SetProperty(ref _statusFilter, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPageIndex
        {
            get => _currentPageIndex;
            set
            {
                if (SetProperty(ref _currentPageIndex, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    OnPropertyChanged(nameof(CanExecuteFirstPage));
                    OnPropertyChanged(nameof(CanExecutePreviousPage));
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set
            {
                if (SetProperty(ref _pageSize, value))
                {
                    // 当每页大小改变时，重置到第一页并重新加载数据
                    CurrentPageIndex = 1;
                    _ = LoadWorkReportQualityDataAsync();
                }
            }
        }

        /// <summary>
        /// 总数量
        /// </summary>
        public int TotalCount
        {
            get => _totalCount;
            set
            {
                if (SetProperty(ref _totalCount, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get => _totalPage;
            set
            {
                if (SetProperty(ref _totalPage, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                if (SetProperty(ref _isLoading, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    OnPropertyChanged(nameof(CanExecuteFirstPage));
                    OnPropertyChanged(nameof(CanExecutePreviousPage));
                    OnPropertyChanged(nameof(CanExecuteNextPage));
                    OnPropertyChanged(nameof(CanExecuteLastPage));
                    OnPropertyChanged(nameof(CanExecuteGoToPage));
                }
            }
        }

        /// <summary>
        /// 跳转页码输入
        /// </summary>
        public string JumpToPage
        {
            get => _jumpToPage;
            set => SetProperty(ref _jumpToPage, value);
        }

        /// <summary>
        /// 分页信息显示
        /// </summary>
        public string PageInfo
        {
            get
            {
                if (IsLoading)
                    return "加载中...";

                if (TotalCount == 0)
                    return "暂无数据";

                return $"第 {CurrentPageIndex} 页，共 {TotalPage} 页，总计 {TotalCount} 条记录";
            }
        }

        #endregion

        #region 命令

        public ICommand SearchCommand { get; }
        public ICommand RefreshCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }
        public ICommand GoToPageCommand { get; }

        /// <summary>
        /// 查看详情命令
        /// </summary>
        public ICommand ViewDetailsCommand { get; }

        #endregion

        #region 命令执行方法

        /// <summary>
        /// 执行搜索
        /// </summary>
        private async void ExecuteSearch()
        {
            CurrentPageIndex = 1;
            await LoadWorkReportQualityDataAsync();
        }

        /// <summary>
        /// 执行刷新
        /// </summary>
        private async void ExecuteRefresh()
        {
            await LoadWorkReportQualityDataAsync();
        }

        /// <summary>
        /// 执行首页
        /// </summary>
        private async void ExecuteFirstPage()
        {
            if (CanExecuteFirstPage())
            {
                CurrentPageIndex = 1;
                await LoadWorkReportQualityDataAsync();
            }
        }

        /// <summary>
        /// 执行上一页
        /// </summary>
        private async void ExecutePreviousPage()
        {
            if (CanExecutePreviousPage())
            {
                CurrentPageIndex--;
                await LoadWorkReportQualityDataAsync();
            }
        }

        /// <summary>
        /// 执行下一页
        /// </summary>
        private async void ExecuteNextPage()
        {
            if (CanExecuteNextPage())
            {
                CurrentPageIndex++;
                await LoadWorkReportQualityDataAsync();
            }
        }

        /// <summary>
        /// 执行末页
        /// </summary>
        private async void ExecuteLastPage()
        {
            if (CanExecuteLastPage())
            {
                CurrentPageIndex = TotalPage;
                await LoadWorkReportQualityDataAsync();
            }
        }

        /// <summary>
        /// 执行跳转页面
        /// </summary>
        private async void ExecuteGoToPage()
        {
            if (int.TryParse(JumpToPage, out int pageNumber) &&
                pageNumber >= 1 && pageNumber <= TotalPage)
            {
                CurrentPageIndex = pageNumber;
                await LoadWorkReportQualityDataAsync();
            }
        }

        /// <summary>
        /// 执行查看详情
        /// </summary>
        private void ExecuteViewDetails(WorkReportQualityItem item)
        {
            if (item == null) return;

            // 触发页面导航事件，通知主窗口切换到详情页面
            RequestNavigateToPage?.Invoke("报工质检详情", item);
        }

        #endregion

        #region 命令可执行判断

        private bool CanExecuteFirstPage() => CurrentPageIndex > 1 && !IsLoading;
        private bool CanExecutePreviousPage() => CurrentPageIndex > 1 && !IsLoading;
        private bool CanExecuteNextPage() => CurrentPageIndex < TotalPage && !IsLoading;
        private bool CanExecuteLastPage() => CurrentPageIndex < TotalPage && !IsLoading;
        private bool CanExecuteGoToPage() => !IsLoading && TotalPage > 0;

        #endregion

        #region 私有方法

        /// <summary>
        /// 加载报工质检数据
        /// </summary>
        private async Task LoadWorkReportQualityDataAsync()
        {
            try
            {
                IsLoading = true;

                var (items, totalCount, totalPage) = await _workReportQualityService.GetWorkReportQualityAsync(
                    CurrentPageIndex, PageSize, OrderNameFilter, StatusFilter);

                WorkReportQualityItems = new ObservableCollection<WorkReportQualityItem>(items);
                TotalCount = totalCount;
                TotalPage = totalPage;
            }
            catch (Exception ex)
            {
                // 这里可以添加错误处理，比如显示消息框
                Console.WriteLine($"加载报工质检数据失败: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 静态刷新事件 - 用于外部触发数据刷新
        /// </summary>
        public static event Action? RefreshDataRequested;

        /// <summary>
        /// 静态方法：触发数据刷新
        /// </summary>
        public static void TriggerRefreshData()
        {
            RefreshDataRequested?.Invoke();
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 取消订阅静态刷新事件
                RefreshDataRequested -= async () => await LoadWorkReportQualityDataAsync();
                _workReportQualityService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}